<?php
declare (strict_types=1);

namespace app\index\controller;

use think\facade\View;
use think\response\Json;
use app\common\model\Cart as CartModel;

class Cart extends Base
{
    public function index()
    {
        $map = ['uid' => $this->user->id];
        $list = CartModel::getList($map, false, 'update_time', ['product']);
        View::assign('list', $list);

        return View::fetch();
    }

    public function add(): Json
    {
        $param = $this->request->post();
        if (!$param['num'] || $param['num'] <= 0) {
            return json(['code' => -1, 'msg' => '数量错误']);
        }

        return json(CartModel::add($this->user, $param['id'], $param['num']));
    }

    public function edit(): Json
    {
        $param = $this->request->post();

        return json(CartModel::edit($param, $this->user->id));
    }

    public function delete(): Json
    {
        $param = $this->request->post();
        CartModel::whereIn('id', $param['cart_id'])->delete();

        return json(['code' => 1, 'msg' => '已删除']);
    }

    public function clear(): Json
    {
        CartModel::where('uid', $this->user->id)->delete();

        return json(['code' => 1, 'msg' => '已清空']);
    }

    public function submit()
    {
        $param = $this->request->post();

        return json(CartModel::submit($param, $this->user));
    }
}